# src/db/connection.py
import pymysql
from pymysql.cursors import DictCursor
from src.config.db_config import DB_CONFIG
from src.utils.logger import get_logger

logger = get_logger(__name__)

def get_db_connection():
    """获取数据库连接（返回DictCursor游标，支持字典格式结果）"""
    try:
        # 替换配置中的cursorclass为实际类
        conn_config = DB_CONFIG.copy()
        conn_config["cursorclass"] = DictCursor
        
        conn = pymysql.connect(**conn_config)
        logger.info("数据库连接成功")
        return conn
    except Exception as e:
        logger.error(f"数据库连接失败：{str(e)}")
        return None

def close_db_connection(conn):
    """关闭数据库连接"""
    if conn and not conn._closed:  # 检查连接是否已关闭
        conn.close()
        logger.info("数据库连接已关闭")